<template>
  <div class="box">
    <button @click="fn1">儿子 - {{ aaaa }} - {{ bbbb }} - {{ cccc }}</button>
  </div>
</template>

<script>
import { inject, hasInjectionContext } from "vue";
export default {
  setup() {
    const aaaa = inject("name");
    const bbbb = inject("age", 18);
    const cccc = inject(
      "sex",
      () => {
        console.log("男");
        return "男";
      },
      // 当第二个参数为函数时，希望函数的返回值才是默认值时，需要将其设置为true
      true
    );
    return {
      aaaa,
      bbbb,
      cccc,
    };
  },

  methods: {
    fn1() {
      console.log(hasInjectionContext(), "===");
      // 在 setup 之外调用 inject()
      const name = inject("name");
      console.log("name", name, "===");
    },
  },
};
</script>
